#coding=utf-8

import io
import os
import sys
import json
import fileinput

from .spine_utils import *
from clitool.core.base.BaseObject import BaseObject
from .PngInfo import PngInfo


class AtlasInfo(BaseObject):
    _fileName = ''
    _name = ''
    _headInfo = {}
    _pictures = []

    @property
    def name(self):
        return self._name
    
    @property
    def headInfo(self):
        return self._headInfo

    @property
    def pictures(self):
        return self._pictures

    def __init__(self):
        super(AtlasInfo, self).__init__(None)
        self._name = ''
        self._headInfo = {}
        self._pictures = []

    def initWithAtlas(self, atlasPath):
        fileIterator = fileinput.input(atlasPath)
        self.__parseHeadInfo(fileIterator)
        self.__parsePictures(fileIterator)

        # if os.path.exists(file_dict['atlas']):
        #     # 打开文件
        #     f = io.open(file_dict['atlas'], 'r', encoding = 'utf-8')
        #     fileIterator = f.readlines()
            
        #     self.__parseHeadInfo(fileIterator)
        #     self.__parsePicsInfo(fileIterator)

        #     f.close() 

        # print(self._headInfo)
        # print("=================================================", self)
        # print(self._pictures)

    def __getNextLine(self, fileIterator):
        for line in fileIterator:
            ret = ''.join(line.split()) #去掉空格
            return ret
        return

    def __parseHeadInfo(self, fileIterator):
        # 第一行空
        self.__getNextLine(fileIterator)

        line = self.__getNextLine(fileIterator)
        self._name = line
        self._fileName = line

        headInfo = {}

        #size
        line = self.__getNextLine(fileIterator)
        headInfo['size'] = getIntArrValue(line)

        #format
        line = self.__getNextLine(fileIterator)
        headInfo['format'] = getStringValue(line)

        #filter
        line = self.__getNextLine(fileIterator)
        headInfo['filter'] = getStringArrValue(line)
        
        #repeat
        line = self.__getNextLine(fileIterator)
        headInfo['repeat'] = getStringValue(line)

        self._headInfo = headInfo

    def __parsePictures(self, fileIterator):

        line = self.__getNextLine(fileIterator)
        while line:
            picInfo = PngInfo()
            self._pictures.append(picInfo)

            name = line.split('/')[-1]  #去掉路径
            picInfo.name = name

            # print("__parsePicsInfo %d %s" %(len(self._pictures), name))


            line = self.__getNextLine(fileIterator)
            rotate = getStringValue(line)
            if rotate == 'false':
                picInfo.rotate = False
            else:
                picInfo.rotate = True

            line = self.__getNextLine(fileIterator)
            picInfo.xy = getIntArrValue(line)

            line = self.__getNextLine(fileIterator)
            picInfo.size = getIntArrValue(line)

            line = self.__getNextLine(fileIterator)
            picInfo.orig = getIntArrValue(line)

            line = self.__getNextLine(fileIterator)
            picInfo.offset = getIntArrValue(line)

            line = self.__getNextLine(fileIterator)
            picInfo.index = getIntValue(line)

            line = self.__getNextLine(fileIterator)

    def readFrom(self, plist_dict):
        metadataDict = plist_dict['metadata']
        self._name = metadataDict['realTextureFileName']
        self._headInfo['size'] = getIntArrValue2(metadataDict['size'])


        framesDict = plist_dict['frames']
        for pic in self._pictures:
            textureDict = framesDict[pic.name + '.png']
            
            intArr = getIntArrValue2(textureDict['frame'])
            # print('--------------------',intArr)
            # print("pic.xy:", pic.xy)
            # print("pic.size:", pic.size)
            pic.xy[0] = intArr[0]
            pic.xy[1] = intArr[1]
            pic.size[0] = intArr[2]
            pic.size[1] = intArr[3]
            # print("pic.xy:", pic.xy)
            # print("pic.size:", pic.size)

            pic.rotate = textureDict['rotated']

    def save(self, outputpath):
        content = []
        content.append('\n')
        content.append('%s\n' % self._name)
        content.append('size: %d, %d\n' % (self._headInfo['size'][0], self._headInfo['size'][1]))
        content.append('format: %s\n' % (self._headInfo['format']))
        content.append('filter: %s, %s\n' % (self._headInfo['filter'][0], self._headInfo['filter'][1]))
        content.append('repeat: %s\n' % self._headInfo['repeat'])

        for pic in self._pictures:
            content.append('%s\n' % pic.name)
            if pic.rotate == True:
                content.append("  rotate: true\n")
            else:
                content.append("  rotate: false\n")
            content.append('  xy: %d, %d\n' % (pic.xy[0], pic.xy[1]))
            content.append('  size: %d, %d\n' % (pic.size[0], pic.size[1]))
            content.append('  orig: %d, %d\n' % (pic.orig[0], pic.orig[1]))
            content.append('  offset: %d, %d\n' % (pic.offset[0], pic.offset[1]))
            content.append("  index: %d\n" % pic.index)

        atlasPath = os.path.join(outputpath, self._fileName.split('.')[0] + '.atlas')
        f = open(atlasPath, 'w+')
        f.writelines(content)

        f.close()





    

